/**
 * Elite jswebbank CTI Client
 * Created by Jeff on 2018/05/17
 */
define([$E.softphoneBasePath + "/softphone/softphone.constants" + $E.jsv], function($CTI_CONST){
	var MSGTYPE = $CTI_CONST.CTI_MSG;
	
	function addJsonStringValue(jsonobj, name, value)
	{
		jsonobj[name.toLowerCase()] = {type: 3, value: value};
	}

	function addJsonIntValue(jsonobj, name, value)
	{
		jsonobj[name.toLowerCase()] = {type: 1, value: value};
	}

	function addJsonDatasValue(jsonobj, name, value)
	{
		jsonobj[name.toLowerCase()] = {type: 5, value: value};
	}

	function getJsonString(jsonobj, name)
	{
		if(jsonobj.hasOwnProperty(name)){
			return jsonobj[name];
		}
		return "";
	}

    function isJson(content){
    	try {
            var jsonStr= JSON.parse(content);
            return true;
    	} catch (e) {
            return false;
    	}
    }

	function isArray(object) {
	    return  object && typeof object==='object' &&    
	            typeof object.length==='number' &&  
	            typeof object.splice==='function' &&    
	             //判断length属性是否是可枚举的 对于数组 将得到false  
	            !(object.propertyIsEnumerable('length'));
	}
	
    function getdatabykey(datas, key) {
    	var d = datas
    	try {
    		if (typeof(d) == 'string') {
    			d = JSON.parse(d);
    		}
    		if (d) {
				for (var vkey in d) {
    				if (vkey.toLowerCase() == key.toLowerCase()) {
    					if (typeof(d)=='object') {
    						if (d.hasOwnProperty('value')) {
    							return d[vkey].value;
    						} else {
    							return d[vkey];
    						}
    					} else {
    						return d[vkey];
    					}
    				}
    			}		    			
    		}
	    } catch (err) {
    		
    	}
    }

    function tosimpleuserdata(datas) {
    	//将随路数据同一成JSON对象。特别地，如果随路数据中包含raw_data或uu_data，则只保留这部分内容
    	try {
    		if (typeof(datas) == 'string') {
    			datas = JSON.parse(datas);
    		}
    		var uui = getdatabykey(datas, 'uu_data');
    		if (uui) {
    			return {'uui' : uui};
    		} else {
    			var uui = getdatabykey(datas, 'raw_data');
    		}
			if (uui) {
				try {
					uui = JSON.parse(uui);
				} catch (err) {
					
				}
				return uui;
			} else {
				//return datas;
				var uui = '';
				var v;
				for (var p in datas) {
					if (datas[p].hasOwnProperty('value')) {
						v = tosimpledata(datas[p].value);
					} else {
						v = datas[p];
					}
					uui = uui + '|' + p + '=' + v;
				}
				uui = uui.substring(1);
				return {'uui': uui};
			}
    	} catch (err) {
    		return {'uui' : datas};
    	}
    }
    
    function tosimpledata(data) {
    	try {
    		if (typeof(data) == 'object') {
        		var jdata = {};
        		for (var p in data) {
        			if (data[p].hasOwnProperty('value')) {
            			jdata[p] = tosimpledata(data[p].value);
        			} else {
        				jdata[p] = data[p];
        			}
        		}
        		return jdata;
    		} else {
    			return data;
    		}
    	} catch (err) {
    		return data;
    	}
    }

    function commonreplace(template, args) {
        if (arguments.length > 1 && typeof arguments[0] === "string") {
            var result = arguments[0];
            if (arguments.length == 2 && typeof arguments[1] === "object") {
                var obj = arguments[1];
                for (var key in obj) {
                    if (obj[key] != undefined) {
                        var reg = new RegExp("({" + key + "})", "g");
                        result = result.replace(reg, obj[key]);
                    }
                }
            } else {
                for (var i = 1, len = arguments.length; i < len; i++) {
                    if (arguments[i] != undefined) {
                        // 这个在索引大于9时会有问题
                        // var reg = new RegExp("({[" + (i - 1) + "]})", "g");
                        var reg = new RegExp("({)" + (i - 1) + "(})", "g");
                        result = result.replace(reg, arguments[i]);
                    }
                }
            }
            return result;
        } else {
            return arguments[0];
        }
    }
    
    var ELITEJSWEBBANKCTIClient = {
		createNew : function(){

			var softphone = {};	
			
			softphone.serverIP = "http://10.107.101.72:38080"
			
			softphone.logined = false;
			softphone.logoutbeforelogin  = 0;
			softphone.keepalivetimer = 0;
			softphone.invokeid = 0;
			softphone.rqqueue = {};
			softphone.currentdest = "";
			softphone.dn = "";
			softphone.channelid = 1;
			softphone.agentid = "";
			softphone.agentpassword = "";
			softphone.agentgroup = "";
			softphone.skillId = "";
			softphone.activeid = "";
			softphone.heldid = "";
			
			softphone.isWork = false;
			
			softphone.skillId = 0;
			
			softphone.eventinterval = 0;	//事件轮询计时器
			
		    var Error = function (error, args) {
		        return this.init(error, args);
		    };
		    Error.UNKNOW_ERROR = {
	            code: 80000,
	            name: "UNKNOW_ERROR",
	            message: "未知错误"
	        };
		    Error.INVOKE_TIMEOUT = {
		        code: 80100,
		        name: "INVOKE_TIMEOUT",
		        message: "请求超时 - {method}"
		    };
		    Error.NO_DEVICE_INFO = {
		        code: 80110,
		        name: "NO_DEVICE_INFO",
		        message: "未获取到分机信息"
		    };
		    Error.INVALID_DEVICE_ID = {
		        code: 80111,
		        name: "INVALID_DEVICE_ID",
		        message: "无效的分机号：{deviceId}"
		    };
		    Error.EXIST_DEVICE_LOGIN = {
		        code: 80112,
		        name: "EXIST_DEVICE_LOGIN",
		        message: "分机已登录，登录工号：{agentId}",
		    };
		    Error.RESOURCE_BUSY = {
		        code: 80113,
		        name: "RESOURCE_BUSY",
		        message: "分机正在通话"
		    };

		    Error.INVALID_AGENT_ID = {
		        code: 80121,
		        name: "INVALID_AGENT_ID",
		        message: "无效的工号：{agentId}"
		    };
		    Error.INVALID_PASSWORD = {
	            code: 80122,
	            name: "INVALID_PASSWORD",
	            message: "无效的密码"
	        };
		    Error.EXIST_AGENT_LOGIN = {
		        code: 80123,
		        name: "EXIST_AGENT_LOGIN",
		        message: "工号已登录，登录分机：{deviceId}"
		    };
		    Error.prototype = {
	            constructor: Error,
	            init: function (error, args) {
	                var newError = null;
	                if (typeof error === "object") {
	                    if (typeof args != undefined) {
	                        newError = Object.create(error);
	                        for (var name in newError) {
	                            newError[name] = commonreplace(newError[name], args);
	                        }
	                    } else {
	                        newError = error;
	                    }
	                } else if (typeof error === "string") {
	                    newError = {
	                        code: 80999,
	                        name: "Error",
	                        message: error
	                    };
	                }
	                return newError;
	            }
	        };

		    softphone.OnCTIEvent = function(evt) {
				this.logmsg("[OnCTIEvent]:" + JSON.stringify(evt));
				this.OnMessage(evt);
			}
					
			softphone.InternalOnError = function(errMessage, errorCode, errorName)
			{
				var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_ERROR);
	        	addJsonIntValue(ret, "dn", this.dn);
	        	addJsonIntValue(ret, "channelid", this.channelid);
	        	if (!errorCode) {
	        		errorCode = 80001
	        	}
	        	addJsonIntValue(ret, "errorcode", errorCode);
	        	addJsonStringValue(ret, "errordesc", errMessage);
	        	if (errorName) {
	        		addJsonStringValue(ret, "errorname", errorName);
	        	}
	            softphone.OnCTIEvent(ret);
			}
			
			softphone.OnAgentLogin = function()
			{
				this.logined = true;
				softphone.isWork = false;
				
				var ret = {};
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_AGENTLOGIN);
	            addJsonIntValue(ret, "workmode", 3);
	            addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            softphone.OnCTIEvent(ret);

	            softphone.getSkill(this.agentid);
	            
	            softphone.setSkill(softphone.skillId);
			}
			
			softphone.OnAgentNotReady = function(jsonobj)
			{
				this.logined = true;
	            var reasoncode = "";
	            var ret = {};
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_AGENTNOTREADY);
	            addJsonIntValue(ret, "workmode", 3);
	            addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            
	            /*
	            if (jsonobj.hasOwnProperty("properties"))
	            {
	                var properties = jsonobj.properties;
	                reasoncode = properties.reason;
	                addJsonIntValue(ret, "reasoncode", reasoncode);
	            }
	            */
	            softphone.OnCTIEvent(ret);   
			}
			
			softphone.OnACW = function(oneEvent)
			{
				softphone.isWork = true;
	            var ret = {};
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_AGENTNOTREADY);
	            addJsonIntValue(ret, "workmode", 4);
	            addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            softphone.OnCTIEvent(ret);   
			}
			softphone.OnAgentReady = function(jsonobj)
			{
				this.logined = true;
				var ret = {};
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_AGENTREADY);
	            addJsonIntValue(ret, "workmode", 2);
	            addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            softphone.OnCTIEvent(ret);
			}
			softphone.OnAgentLogout = function(jsonobj)
			{
				if (this.logoutbeforelogin == 1) {
					this.logoutbeforelogin = 2;
					return;
				}
				this.logined = false;
				var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_AGENTLOGOUT);
				addJsonIntValue(ret, "workmode", 0);
				addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            
	            softphone.stopCircleEvent(softphone.eventinterval);
	            //softphone.unRegisterDN();
	            softphone.OnCTIEvent(ret);

	            var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_LINKDISCONNECTED);
				softphone.OnCTIEvent(ret);
			}
			
			softphone.OnRinging = function(oneEvent)
			{
				softphone.activeid = "id1";
				softphone.logmsg("in OnRinging,  activeid=" + softphone.activeid + ", heldid=" + softphone.heldid);
				
				var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_RINGING);
				addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            var ani = oneEvent.ani;
	            var dnis = oneEvent.dnis;
	            var otherdn = oneEvent.otherDN;
	            var callid = oneEvent.callid;
	            if (!ani || ani == 'null') {
	            	ani = otherdn;
	            }
	            addJsonStringValue(ret, "ani", ani);
	            addJsonStringValue(ret, "dnis", dnis);
	            if (otherdn) {
	            	addJsonStringValue(ret, "otherdn", otherdn);
	            }
	            addJsonStringValue(ret, "callid", callid);
	            addJsonStringValue(ret, "connectionid", "id1")
	            softphone.OnCTIEvent(ret);
			}
			softphone.OnDialing = function(oneEvent)
			{
				softphone.activeid = "id1";
				softphone.logmsg("in OnDialing, activeid=" + softphone.activeid + ", heldid=" + softphone.heldid);
				var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_DIALING);
				addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            var ani = oneEvent.ani;
	            var dnis = oneEvent.dnis;
	            var otherdn = oneEvent.otherDN;
	            var callid = oneEvent.callid;
	            if (!dnis || dnis == 'null') {
	            	dnis = otherdn;
	            }
	            if (!ani || dnis == 'null') {
	            	ani = this.dn;
	            }
	            addJsonStringValue(ret, "ani", ani);
	            addJsonStringValue(ret, "dnis", dnis);
	            if (otherdn) {
	            	addJsonStringValue(ret, "otherdn", otherdn);
	            }
	            addJsonStringValue(ret, "callid", callid);
	            addJsonStringValue(ret, "connectionid", "id1");
	            softphone.OnCTIEvent(ret);
			}
			
			softphone.OnRingback = function(oneEvent)
			{
				var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_RINGBACK);
				addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            var ani = oneEvent.ani;
	            var dnis = oneEvent.dnis;
	            var otherdn = oneEvent.otherDN;
	            var callid = oneEvent.callid;
	            if (!dnis || dnis == 'null') {
	            	dnis = otherdn;
	            }
	            if (!ani || dnis == 'null') {
	            	ani = this.dn;
	            }
	            addJsonStringValue(ret, "ani", ani);
	            addJsonStringValue(ret, "dnis", dnis);
	            if (otherdn) {
	            	addJsonStringValue(ret, "otherdn", otherdn);
	            }
	            addJsonStringValue(ret, "callid", callid);
	            addJsonStringValue(ret, "connectionid", "id1");
	            softphone.OnCTIEvent(ret);
			}
			
			softphone.OnEstablished = function(oneEvent)
			{
				var ret = {};
				addJsonIntValue(ret, "event", MSGTYPE.EVT_ESTABLISH);
				addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            var ani = oneEvent.ani;
	            var dnis = oneEvent.dnis;
	            var otherdn = oneEvent.otherDN;
	            var callid = oneEvent.callid;
	            if (!dnis || dnis == 'null') {
	            	dnis = otherdn;
	            }
	            if (!ani || ani == 'null') {
	            	ani = this.dn;
	            }
	            addJsonStringValue(ret, "ani", ani);
	            addJsonStringValue(ret, "dnis", dnis);
	            if (otherdn) {
	            	addJsonStringValue(ret, "otherdn", otherdn);
	            }
	            addJsonStringValue(ret, "callid", callid);
	            addJsonStringValue(ret, "connectionid", "id1");
				softphone.activeid = "id1";
				softphone.logmsg("in OnEstablished, activeid=" + softphone.activeid + ", heldid=" + softphone.heldid);
	            
	            softphone.OnCTIEvent(ret);
			}
			softphone.OnConnectionCleared = function(oneEvent)
			{
				if (softphone.activeid || softphone.heldid) {
					softphone.activeid = "";
					softphone.heldid = "";
					softphone.logmsg("in OnConnectionCleared, activeid=" + softphone.activeid + ", heldid=" + softphone.heldid);
					var ret = {};
					addJsonIntValue(ret, "event", MSGTYPE.EVT_RELEASED);
					addJsonStringValue(ret, "dn", this.dn);
					addJsonIntValue(ret, "channelid", this.channelid);
		            var callid = oneEvent.callid;
		            addJsonStringValue(ret, "callid", callid);
		            addJsonStringValue(ret, "connectionid", "id1");
		            softphone.OnCTIEvent(ret);
				} else {
					softphone.logmsg("::OnConnectionCleared with no activeid and heldid")
				}
			}
			softphone.OnHeld=function(jsonobj)
			{
				softphone.heldid = "id1";
				softphone.activeid = "";
				softphone.logmsg("in OnHeld, activeid=" + softphone.activeid + ", heldid=" + softphone.heldid);
				var ret = {};
	            var properties = jsonobj.properties;
	            var holdingdevice = getJsonString(properties, "holdingDevice");
	            
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_HELD);
	            var callid = oneEvent.callid;
	            addJsonStringValue(ret, "callid", callid);
	            addJsonStringValue(ret, "connectionid", "id1");
	            
	            softphone.OnCTIEvent(ret);
			}
			softphone.OnRetrieved = function(jsonobj)
			{
				softphone.activeid = "id1";
				softphone.heldid = "";
				softphone.logmsg("in OnRetrieved, activeid=" + softphone.activeid + ", heldid=" + softphone.heldid);
				var ret = {};
	            var properties = jsonobj.properties;
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_RETRIEVED);
	            addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            
	            var callid = getJsonString(properties, "callId");
	            this.activeid = callid;
	            addJsonStringValue(ret, "callid", callid);
	            if (callid == this.heldid)
	            {
	                this.heldid = "";
	            }
	            return ret;
			}
			softphone.OnTransferred = function(jsonobj) {
				var ret = [];
				var properties = jsonobj.properties;
	            var transferringDevice = getJsonString(properties, "transferringDevice");
	            
	            if (transferringDevice == this.dn) {
	                var evt = {};
	                addJsonStringValue(evt, "DN", this.dn);
	                addJsonIntValue(evt, "channelid", this.channelid);
	                addJsonIntValue(evt, "event", MSGTYPE.EVT_RELEASED);
	                var primaryOldCallID=getJsonString(properties, "primaryOldCall");
	                addJsonStringValue(evt, "callid", primaryOldCallID);
	                addJsonStringValue(evt, "transferreleased", 1);
	                ret[0] = evt;
	                var evt2 = {};
	                addJsonStringValue(evt2, "dn", this.dn);
	                addJsonIntValue(evt2, "channelid", this.channelid);
	                addJsonIntValue(evt2, "event", MSGTYPE.EVT_RELEASED);
	                var secondaryOldCallID = getJsonString(properties, "secondaryOldCall");
	                addJsonStringValue(evt2, "callid", secondaryOldCallID);
	                addJsonIntValue(evt2, "transferreleased", 1);
	                ret[1] = evt2;
	                this.activeid = "";
	                this.heldid = "";
	            } else {
	                var evt = {};
	                addJsonStringValue(evt, "dn", this.dn);
	                addJsonIntValue(evt, "channelid", this.channelid);
	                addJsonIntValue(evt, "event", MSGTYPE.EVT_PARTYCHANGED);
	                var primaryOldCallID=getJsonString(properties, "primaryOldCall");
			        var secondaryOldCallID = getJsonString(properties, "secondaryOldCall");
			        addJsonStringValue(evt, "activecallid", secondaryOldCallID);
			        addJsonStringValue(evt, "heldcallid", primaryOldCallID);
	                ret[0] = evt;
	                if (this.activeid == primaryOldCallID) {
	                	this.activeid = secondaryOldCallID;
	                } else if (this.heldid == primaryOldCallID) {
	                	this.heldid = secondaryOldCallID
	                }
	            }
	            return ret;
			}
			softphone.OnConferenced = function(jsonobj)
			{
				var ret = {};
				var properties = jsonobj.properties;
				addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            var cause=getJsonString(properties, "cause");
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_CONFERENCED);
	            if(cause == "31"){
	            	addJsonIntValue(evt, "SILENTMONITOR", 1);
		        }
	            var primaryOldCallID=getJsonString(properties, "primaryOldCall");
	            var secondaryOldCallID = getJsonString(properties, "secondaryOldCall");
	            addJsonStringValue(ret, "activecallid", secondaryOldCallID);
	            addJsonStringValue(ret, "heldcallid", primaryOldCallID);
	            
	            addJsonStringValue(ret, "callid", this.activeid);
	            if (this.heldid && this.heldid != this.activeid) {
	            	addJsonStringValue(ret, "prevconnectionid", this.heldid);
	            }

	            var addedParty=getJsonString(properties, "addedParty");
		        if(addedParty != ""){
		        	addJsonStringValue(ret, "addedparty", addedParty);
	            }
	            var contactid=getJsonString(properties, "contactId");
	            var userdatas = {};
	            addJsonStringValue(ret, "ucid", contactid);
	            addJsonDatasValue(ret, "userdata", userdatas);
	            return ret;
			}
			softphone.OnAgentACW = function(jsonobj)
			{
				var ret = {};
				this.logined = true;
	            var properties = jsonobj.properties;
	            var reasoncode = getJsonString(properties, "reason");
	            addJsonIntValue(ret, "event", MSGTYPE.EVT_AGENTNOTREADY);
	            addJsonIntValue(ret, "workmode", 4);
	            addJsonStringValue(ret, "dn", this.dn);
	            addJsonIntValue(ret, "channelid", this.channelid);
	            return ret;
			}
			
			softphone.keepalive = function()
			{
				
			}

			softphone.connectserver = function(serverendpoint, onOpen, onClose, onMessage, onError, onSendMessage){
				softphone.OnSendMessage = onSendMessage;
				softphone.OnMessage = onMessage;
				softphone.OnError = onError;
				
				var evt = {};
				addJsonIntValue(evt, "event", MSGTYPE.EVT_LINKCONNECTED);
				softphone.OnCTIEvent(evt);
			};
			
			softphone.logmsg = function(msg)
			{
		    	if (typeof(evt) == 'string') {
					console.log("[_jswebbank]" + JSON.stringify(msg));
		    		
		    	} else {
					console.log("[_jswebbank]" + msg);
		    	}
			}
			
			softphone.LeftFill = function(s, len, fillchar)
			{
				var ret = "";
				for (var i = s.length; i < len; i++)
				{
					ret = ret + fillchar;;
			    }
				return ret + s;
			}
			
			softphone.RightFill = function(s,len,fillchar)
			{
				var ret = "";
				for (var i = s.length; i < len; i++)
				{
					ret=ret + fillchar;;
				}
				return s + ret;
			}

			softphone.registerdn = function(dn)
		    {
		    	this.dn = dn;
				var evt = {};
				addJsonIntValue(evt, "dn", this.dn);
	        	addJsonIntValue(evt, "channelid", this.channelid);
	        	addJsonIntValue(evt, "event", MSGTYPE.EVT_REGISTERED);
		    	softphone.OnCTIEvent(evt); 
		    };
		    softphone.unRegisterDN = function()
		    {
				var evt = {};
				addJsonIntValue(evt, "dn", this.dn);
	        	addJsonIntValue(evt, "channelid", this.channelid);
	        	addJsonIntValue(evt, "event", MSGTYPE.EVT_UNREGISTERED);
		    	softphone.OnCTIEvent(evt); 
		    }
			    
			softphone.sendRequest = function(url, op, succfunc, errfunc)
			{
			    softphone.logmsg("::sendRequest, op = " + op + ", url = " +url);
			    $.ajax({
			        type: "get",
			        url: url,
			        dataType: "jsonp",
			        jsonp: "jsonpCallback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
			        success: function (json) {
			        	console.log("::sendRequest, op = " + op + ", success = -->");
			        	console.log(JSON.stringify(json));
			            result_Code = json.resultCode;
		                var resultCode = json.resultCode;
			            if (resultCode != 0 && resultCode != 'null') {
			                console.log("错误码:" + resultCode);
			            }
			            if (succfunc) {
			            	succfunc(json);
			            }
			        },
			        error: function () {
			        	console.log("::sendRequest, op = " + op + ", error");
			            //alert('fail');
			        	if (errfunc) {
			        		errfunc();
			        	}
			        }
			    });
			}
			
			//轮询事件
			softphone.circleEvent = function(agentId) {
			    softphone.eventinterval = setInterval(function () {
			        softphone.getAgentEvent(agentId);
			    }, 500);
			}
			//停止时间轮询
			softphone.stopCircleEvent = function(interval) {
			    window.clearInterval(interval);
			}

			//获取坐席事件
			softphone.getAgentEvent = function(agentId)
			{
			    var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=getEvent&agentId=" + agentId + "&skillId=" + softphone.skillId;
			    softphone.getEvent(url);
			}
			
			//获取事件
			softphone.getEvent = function(url)
			{
			    $.ajax({
			        type: "get",
			        url: url,
			        dataType: "jsonp",
			        jsonp: "jsonpCallback",
			        success: function (json) {
			            var result = json.event;
			            if (result != null) {
			        		softphone.logmsg("::getEvent, success = -->");
			        		softphone.logmsg(JSON.stringify(json));
			                var jsonData = eval('(' + result + ')');
			                softphone.agentEventHandle(jsonData);
			                setTimeout(function(){softphone.getEvent(url)},10);
			            }
			        },
			        error: function () {
						softphone.logmsg("::getEvent, error");
			            softphone.stopCircleEvent(softphone.eventinterval);
			        }
			    });
			}
			
			//登录
			softphone.login = function(agentid,dn,agentpassword,agentgroup,workmode,acdagent)
			//softphone.login = function(agentId, number)
			{
		    	this.agentid = agentid;
		    	this.dn = dn;
		    	this.agentpassword = agentpassword;
		    	this.agentgroup = agentgroup;
		    	
		    	if (isNaN(agentgroup)) {
		    		this.skillId = 51;
		    	} else {
		    		this.skillId = Number(agentgroup);
		    	}
		    	
		    	
		    	var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=login&agentId=" + agentid + "&password="+agentpassword+"&number=" + dn;
			    softphone.sendRequest(url, 'login',
			    	function(json) {
			    		if (json.resultCode == 0) {
			    			//"签入成功";
			    			softphone.circleEvent(agentid);
			    		} else if (json.resultCode == '100-002') {
			    			//"签入失败[坐席已签入]";
			    		} else if (json.resultCode == '100-011') {
			    			//"签入失败[分机已签入]";
			    		} else {
			    			//"签入失败["+json.resultCode+"]";
			    		}
			    	},
			    	function() {
			    	
			    	}
			    )
			}

		    softphone.agentlogout = function()
		    {
			    var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=logout&agentId=" + this.agentid + "&number=" + this.dn;
			    softphone.sendRequest(url, 'logout',
			    	function(json) {
			    		if (json.resultCode == 0) {
			    			//"签出成功";
			    		}
			    	},
			    	function() {
			    	
			    	}
			    )
		    }
		    
		    softphone.agentnotready = function()
		    {
		    	return softphone.aux(0);
		    }

		    softphone.aux = function(reasoncode)
			{
		    	softphone.clearWork();
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=notReady&agentId=" + this.agentid;
		        softphone.sendRequest(url, "agentnotready");
			}
		    
		    //后处理
		    softphone.acw = function()
		    {
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=acw&agentId=" + this.agentid;
		        softphone.sendRequest(url, "acw");
		    }

		    //示闲
		    softphone.agentready = function(workmode)
		    {
		    	if (softphone.clearWork() == 1) {
		    		softphone.agentnotready();
		    	};
		    	var atemp = false;
		    	if (atemp) {
		    		return;
		    	}
		    	var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=idle&agentId=" + this.agentid;
		        softphone.sendRequest(url, "agentready");
		    }

		    softphone.clearWork = function()
		    {
		    	if (softphone.isWork) {
		    		var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=acw&agentId=" + this.agentid;
		    		softphone.sendRequest(url, "clearWork");
		    		return 1;
		    	}
		    	return 2;
		    }
		    //外呼
		    softphone.makecall = function(dest, userdatas)
		    {
		    	//var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=dial&agentId=" + this.agentid + "&number=" + dest + "&skillId=" + softphone.skillId + "&addFlag=0";
		    	var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=dial&agentId=" + this.agentid + "&number=" + dest + "&skillId=" + softphone.skillId + "&addFlag=";
		    	softphone.sendRequest(url, "makecall");
		    }

		    //挂断
		    softphone.releasecall = function(callid)
		    {
		        //releaseFlag   0:接通前挂断   1:接通后挂断
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=release&agentId=" + this.agentid + "&skillId=" + softphone.skillId;
		        //if (releaseFlag == 0) {
		        //    url = serverIP + "/hwsoftphone/softphoneServlet?method=release&agentId=" + agentId + "&skillId=100";
		        //}
		        softphone.sendRequest(url, "releasecall");
		        
		    }

		    //接听
		    softphone.answercall = function(callid)
		    {
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=answer&agentId=" + this.agentid;
		        softphone.sendRequest(url, "answercall");
		    }

		    //保持保持
		    softphone.holdcall = function(callid) {
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=hold&agentId=" + this.agentid;
		        softphone.sendRequest(url, "holdcall");
		    }
		    //取保持
		    softphone.retrievecall = function(callid) {
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=unhold&agentId=" + this.agentid + "&callId=" + callid;
		        softphone.sendRequest(url, "retrievecall");
		    }
		    //转接
		    softphone.transfer = function() {
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=sinleTran&agentId=" + this.agentid + "&targetNum=" + selectedNunber;
		        softphone.sendRequest(url, "transfer");
		    }
		    //获取技能组
		    softphone.getSkill = function(agentId){
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=getSkill&agentId=" + agentId;
		        softphone.sendRequest(url, 'getSkill',
		        		function(json) {
			               if (json.skill != null) {
			                    var skill = json.skill;
			                    var jsonresult = eval('(' + skill + ')');
			                    for (var i = 0; i < jsonresult.length; i++) {
			                        var name = decodeURI(jsonresult[i].name);
			                        var id = jsonresult[i].id;
			                        softphone.logmsg("技能组ID:" + id + "---技能组名字:" + name);
			                    }
			                }
		        		},function(){
		        	
		        		}
		       	)
		    }
		    //设置技能组
		    softphone.setSkill = function(agentId, skillId) {
		        var url = softphone.serverIP + "/hwsoftphone/softphoneServlet?method=setSkill&agentId=" + agentId + "&skillId=" + skillId;
		        softphone.sendRequest(url, 'setSkill', 
		        		function(json)
		        		{
		        			/*
		                    var resultCode = json.resultCode;
			                if (resultCode != 0 && resultCode != 'null') {
			                    console.log("错误码:" + resultCode);
			                }
			                */
		        		},
		        		function()
		        		{
		        			
		        		}
		        )
		    }
		    
		    softphone.agentEventHandle = function(oneEvent)
		    {
		    	var eventType = oneEvent.EventType;

		    	if(eventType == "AgentState_CancelNotReady_Success"){
		    		//if(checkIdea == 0){
		    		//	eventType = "AgentOther_PhoneOffhook";
		    		//	console.log("非坐席手动示闲，转换事件为AgentOther_PhoneOffhook");
		    		//}
		    		if (softphone.activeid || softphone.heldid) {
		    			eventType = "AgentOther_PhoneOffhook";
		    			softphone.logmsg("非坐席手动示闲，转换事件为AgentOther_PhoneOffhook")
		    		}
		    	}

		    	switch(eventType)
		    	{
		    	/****************************坐席状态事件****************************/
		    	
		    	case "AgentState_SetNotReady_Success":      // 座席示忙成功
		    	case "AgentState_Force_SetNotReady":        // 座席被平台强制示忙
		    		softphone.OnAgentNotReady();
		    		break;

		    	case "AgentState_Ready":                   // 普通示闲事件
		    	case "AgentState_Force_Ready":             // 座席被强制示闲
		    	case "AgentState_CancelNotReady_Success":  // 座席取消示忙成功
		    		softphone.OnAgentReady();
		    		break;
		    	case "AgentState_CancelRest_Success":      // 坐席取消休息成功
		    	case "AgentState_CancelWork_Success":      // 坐席退出工作态成功
		    		//Proc_CancelWork_Success();
		    		break;

		    	case "AgentState_SetRest_Success":        // 坐席请求休息成功
		    		//Proc_agentState_rest();
		    		break;
		    		
		    	case "AgentState_Rest_Timeout":           // 休息时间超过申请时间事件
		    		//Proc_agentState_restTimeout();
		    		break;

		    	case "AgentState_SetWork_Success":       // 坐席进入工作态成功
		    	case "AgentState_Work":
		    		//Proc_agentState_work();
		    		softphone.OnACW(oneEvent);
		    		break;

		    	case "AgentState_Busy":
		    		//Proc_agentState_busy();
		    		break;
		    			
		    		
		    	/****************************其它坐席相关事件****************************/
		    		
		    	case "AgentOther_WasSwaped":        // 服务器切换事件
		    		//Proc_server_wasSwaped();
		    		break;
		    	case "AgentOther_ShutdownService":  // 座席签出事件
		    		softphone.OnAgentLogout();
		    		break;
		    	case "AgentOther_InService":        // 座席签入事件
		    		softphone.OnAgentLogin();
		    		break;
		    	case "AgentOther_PhoneAlerting":    // 座席物理话机振铃事件
		    		//Proc_agentPhone_alerting();
		    		softphone.OnDialing(oneEvent);
		    		break;
		    	case "AgentOther_PhoneOffhook":     // 座席物理话机摘机事件
		    		//Proc_agentPhone_offhook();
		    		break;
		    	case "AgentOther_PhoneRelease":     // 座席物理话机挂机事件
		    		//Proc_agentPhone_release();
		    		break;
		    	case "AgentOther_PhoneUnknow":      // 座席物理话机状态未知事件
		    		//Proc_agentPhone_unknow();
		    		break;
		    	case "AgentOther_Note":             // 收到便签
		    		//Proc_agentEvent_note(oneEvent);
		    		break;
		    	case "AgentOther_Bulletin":         // 收到公告
		    		//Proc_agentEvent_Bulletin(oneEvent);
		    		break;
		    	case "AgentOther_All_Agent_Busy":   // 所有坐席全忙
		    		//Proc_agentEvent_allBusy(oneEvent);
		    		break;


		    	case "AgentOther_CallOutPrivateQueue"://呼叫从私有队列中删除
		    		//Proc_agentEvent_callOutPrivateQueue(oneEvent);
		    		break;


		    	case "AgentOther_CallInPrivateQueue"://呼叫进入私有队列中
		    		//Proc_agentEvent_callInPrivateQueue(oneEvent);
		    		break;
		    		

		    	/****************************座席语音通话相关事件****************************/	
		    	
		    	case "AgentEvent_Customer_Alerting":  //1.座席相关用户振铃事件
		    		//softphone.OnDialing(oneEvent);
		    		softphone.OnRingback(oneEvent);
		    		break;
		    	case "AgentEvent_Ringing":            //2.座席振铃事件
		    		softphone.OnRinging(oneEvent);
		    		break;
		    	case "AgentEvent_Hold":               //3.座席保持事件
		    		softphone.OnHeld(oneEvent);
		    		break;
		    	case "AgentEvent_Talking":            //4.座席通话事件
		    		softphone.OnEstablished(oneEvent);
		    		break;
		    	case "AgentEvent_Conference":         //5.座席通话事件
		    		//Proc_agentEvent_conference(oneEvent);
		    		break;
		    	case "AgentEvent_Call_Out_Fail":       //6.座席外呼失败事件
		    		//Proc_agentEvent_outBoundFail(oneEvent);
		    		break;
		    	case "AgentEvent_Inside_Call_Fail":     //7.座席内部呼叫失败事件
		    		//Proc_agentEvent_insideCallFail(oneEvent);
		    		break;
		    	case "AgentEvent_Call_Release":        //8.座席挂机事件
		    		softphone.OnConnectionCleared(oneEvent);
		    		break;
		    	case "AgentEvent_No_Answer":
		    		//Proc_agentEvent_No_Answer(oneEvent);
		    		break;
		    	case "AgentEvent_Customer_Release":        //9.座席挂机事件
		    		softphone.OnConnectionCleared(oneEvent);
		    		break;
		    	case "AgentEvent_Auto_Answer":         //10.座席自动应答事件
		    		//Proc_agentEvent_autoAnswer(oneEvent);
		    		break;
		    	case "AgentEvent_Connect_Fail":        //11.座席连接失败事件
		    		//Proc_agentEvent_connectFail(oneEvent);
		    		break;
		    	case "AgentEvent_Preview":            //12.座席预览事件
		    		//Proc_agentEvent_preview(oneEvent);
		    		break;
		    	case "AgentEvent_Release_Preview":     //13.座席释放预览事件
		    		//Proc_agentEvent_releasePreview();
		    		break;
		    	case "AgentEvent_Agent_Occupyed":    //14.座席预占事件
		    		//Proc_agentEvent_agentBeOccupyed();
		    		break;
		    	case "AgentEvent_Consult_Fail":       //内部求助失败事件
		    		//Proc_agentEvent_consultFail(oneEvent);
		    		break;
		    		
		    	/**--------------------- 座席媒体事件 --------------------------*/
		    	
		    	case "AgentMediaEvent_Play":    //座席媒体事件，播放
		    		//Proc_agentMediaEvent_play();
		    		break;
		    	case "AgentMediaEvent_PlayDone"://座席媒体事件，播放完成
		    		//Proc_agentMediaEvent_playDone();
		    		break;
		    	case "AgentMediaEvent_StopPlayDone":    //座席媒体事件，停止
		    		//Proc_agentMediaEvent_stop();
		    		break;
		    	case "AgentMediaEvent_PausePlayDone":   //座席媒体事件，暂停
		    		//Proc_agentMediaEvent_pause();
		    		break;
		    	case "AgentMediaEvent_ResumePlayDone":  //座席媒体事件，继续
		    		//Proc_agentMediaEvent_resume();
		    		break;
		    	case "AgentMediaEvent_JumpPlayDone":    //座席媒体事件，跳进
		    		//Proc_agentMediaEvent_jump();
		    		break;
		    	case "AgentMediaStatus_Play":   //座席媒体状态，播放
		    		//Proc_agentMediaStatus_play();
		    		break;
		    	case "AgentMediaStatus_Stop":   //座席媒体状态，停止
		    		//Proc_agentMediaStatus_stop();
		    		break;
		    	case "AgentMediaStatus_Pause":  //座席媒体状态，暂停
		    		//Proc_agentMediaStatus_pause();
		    		break;

		    	case "AgentMediaEvent_Record":   //座席录音开始
		    		/** Begin add by jinsitao for DTS2012080606854  录音开始*/
		    		//Proc_agentMediaEvent_record();
		    		break;
		    	case "AgentMediaEvent_RecordDone": //座席录音完成
		    		break;
		    	case "AgentMediaEvent_PauseRecordDone": //座席暂停录音成功事件
		    		break;
		    	case "AgentMediaEvent_ResumeRecordDone":  //座席恢复录音成功事件
		    		break;
		    	case "AgentMediaEvent_StopRecordDone":  //座席停止录音成功
		    		/** Begin add by jinsitao for DTS2012080606854  录音停止*/
		    		//Proc_agentMediaEvent_stopRecordDone();
		    		break;

		    		
		    	/**--------------------------文字交谈事件--------------------------------*/
		    	case "AgentChat_DataRecved":  //接收文字交谈内容
		    		//Proc_AgentChat_DataRecved(oneEvent);
		    		break;

		    	case "AgentChat_Disconnected":
		    		//Proc_AgentChat_Disconnected(oneEvent);
		    		break;

		    	case "AgentChat_Connected": //
		    		//Proc_AgentChat_Connected(oneEvent);
		    		break;

		    	case "AgentChat_Ring":  //文件交谈请求事件
		    		//Proc_AgentChat_Ring(oneEvent);
		    		break;

		    	case "AgentChat_TransferStart":
		    		//Proc_AgentChat_TransferStart(oneEvent);
		    		break;

		    	case "AgentChat_TransferFailed":
		    		//Proc_AgentChat_TransferFailed(oneEvent);
		    		break;

		    	case "AgentChat_CalloutFailed":
		    		//Proc_AgentChat_CalloutFailed(oneEvent);
		    		break;

		    	//事后处理邮件
		    	case "AgentChat_DELAY_EMAIL":
		    		//Proc_AgentChat_DelayEmail(oneEvent);
		    		break;
		    		
		    	/*******************会议模拟事件开始*********************/
		    	case "AgentChat_ChatRoom_Ring": //
		    		//Proc_AgentChat_ChatRoom_Ring(oneEvent);
		    		break;

		    	case "AgentChat_ChatRoom_Connected":  //
		    		//Proc_AgentChat_ChatRoom_Connected(oneEvent);
		    		break;
		    	case "AgentChat_ChatRoom_Success":  //
		    		//Proc_AgentChat_ChatRoom_Success(oneEvent);
		    		break;

		    	case "AgentChat_ChatRoom_DataRecved":  //
		    		//Proc_AgentChat_ChatRoom_DataRecved(oneEvent);
		    		break;

		    	case "AgentChat_ChatRoom_Disconnected":  //
		    		//Proc_AgentChat_ChatRoom_Disconnected(oneEvent);
		    		break;
		    		
		    	/*******************会议模拟事件结束*********************/
		    	
		    	/**附件发送**/
		    	case "AgentChat_AttachRequest": //对方发起请求接收
		    		//Proc_AgentChat_AttachRequest(oneEvent);
		    		break;

		    	case "AgentChat_AttachAccepted": //对方确认接收
		    		//Proc_AgentChat_AttachAccepted(oneEvent);
		    		break;

		    	case "AgentChat_AttachRejected": //对方拒绝接受
		    		//Proc_AgentChat_AttachRejected(oneEvent);
		    		break;

		    	case "AgentChat_AttachFinished": //对方接受完成
		    		//Proc_AgentChat_AttachFinished(oneEvent);
		    		break;

		    	case "AgentChat_AttachAborted": //对方取消发送
		    		//Proc_AgentChat_AttachAborted(oneEvent);
		    		break;


		    	case "AgentChat_AttachTransfer": //对方附件发送完成
		    		//Proc_AgentChat_AttachTransfer(oneEvent);
		    		break;

		    	/**-------------------------- 实时质检 --------------------------**/
		    	case "QC_AgentState_Notify":
		    		//Proc_QC_AgentState_Notify(oneEvent);
		    		break;
		    		
		    	/**-------------------------- 实时质检 --------------------------**/
		    	case "AgentEvent_Orders_Notify":
		    		//Proc_AgentEvent_Orders_Notify(oneEvent);
		    		break;
		    		
		    	/**-------------------------- 桌面共享--------------------------**/	
		    	case "AgentChat_ScreenShareRequest"://表示收到对方的桌面共享请求
		    		//Proc_AgentChat_ScreenShareRequest(oneEvent);
		    		break;
		    	case "AgentChat_ScreenShareReject"://表示对方拒绝了屏幕共享的请求
		    		//Proc_AgentChat_ScreenShareReject(oneEvent);
		    		break;
		    	case "AgentChat_ScreenShareStart"://表示开始屏幕共享，座席收到改事件，调用控件的doJoinSession加入共享（共享屏幕的座席收到).
		    		//Proc_AgentChat_StartScreenShare(oneEvent);
		    		break;
		    	case "AgentChat_ScreenShareAborted":// 表示屏幕共享异常终止了，座席需要调用控件的doExitSession
		    		//Proc_AgentChat_ScreenShareAborted(oneEvent);
		    		break;
		    	case "AgentChat_ScreenShareFinish":// 表示屏幕共享正常结束，座席需要调用控件的doExitSession
		    		//Proc_AgentChat_ScreenShareFinish(oneEvent);
		    		break;
		    		
		    	/***------服务器发生主备切换---------------------------**/
		    	case "AgentChat_Swaped":
		    		//Proc_AgentChat_Swaped(oneEvent);
		    		break;

		    	/***------获取服务中转IVR随路数据---------------------------**/
		        case "SERVER_TO_IVR_DH":
		    		//Proc_Server_to_IVR_DH(oneEvent);
		    		break;

		    	/***------获取服务中信息更新随路数据---------------------------**/
		        case "SERVER_TO_IVR_MESSAGE_UPDATE":
		    		//Proc_Server_to_IVR_MessageUpdate(oneEvent);
		    		break;

		    	default:
		    		//alert("目前无该事件处理   " + eventType);

		    	}
		    }

	        return softphone;
		}
	};
	
	return ELITEJSWEBBANKCTIClient.createNew();
	
});
